package dao;

import java.util.List;

import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.criterion.Restrictions;

import beans.Card;

import utils.HibernateUtil;






public class CardDao {
	private SessionFactory sessionFactory;

	public CardDao() {
		sessionFactory = HibernateUtil.getSessionFactory();
	}

	Transaction tr = null;
	
	/**
	 * 删除授权卡
	 */
	public void delete(Card card) {
		Session session = sessionFactory.openSession();
		tr = session.beginTransaction();
		session.delete(card);
		tr.commit();
		session.close();
	}
	
	/**
	 * 修改授权卡
	 */
	public void edit(Card card) {

		Session session = sessionFactory.openSession();
		tr = session.beginTransaction();
		session.update(card);
		tr.commit();
		session.close();
	}
	
	/**
	 * 修改授权卡
	 */
	public void change(Card card,int status) {
		Session session = sessionFactory.openSession();
		tr = session.beginTransaction();
		card.setStatus(status);
		session.update(card);
		tr.commit();
		session.close();
	}
	
	/**
	 * 保存新增的授权卡
	 */
	public void save(Card card) {
		Session session = sessionFactory.openSession();
		tr = session.beginTransaction();
		session.save(card);
		tr.commit();
		session.close();
	}
	
	/**
	 * 返回所有授权卡信息
	 */
	public List<Card> getAllCard(){
		Session session=sessionFactory.openSession();
		tr=session.beginTransaction();
		Criteria c=session.createCriteria(Card.class);
		List<Card> cards=c.list();
		tr.commit();
		session.close();
		return cards;
	}
	
	/**
	 * 返回所有授权卡信息
	 */
	public List<Card> getSernumCard(String sernum){
		Session session=sessionFactory.openSession();
		tr=session.beginTransaction();
		Criteria c=session.createCriteria(Card.class);
		c.add(Restrictions.eq("sernum", sernum));
		List<Card> cards=c.list();
		tr.commit();
		session.close();
		return cards;
	}
	
	public List<Card> getByRfid(String rfid){
		Session session=sessionFactory.openSession();
		tr=session.beginTransaction();
		Criteria c=session.createCriteria(Card.class);
		c.add(Restrictions.eq("rfid", rfid));
		List<Card> cards=c.list();
		tr.commit();
		session.close();
		return cards;
	}
	
	/**
	 * 返回所有管理员授权卡信息
	 */
	public List<Card> getAdminCard(){
		Session session=sessionFactory.openSession();
		tr=session.beginTransaction();
		Criteria c=session.createCriteria(Card.class);
		List<Card> cards=c.list();
		tr.commit();
		session.close();
		return cards;
	}

	/**
	 * 通过授权卡ID返回指定授权卡信息
	 * 
	 * @return
	 */
	public Card getCardById(int cardId) {
		Session session = sessionFactory.openSession();
		tr = session.beginTransaction();
		Card card = (Card) session.get(Card.class, cardId);
		tr.commit();
		session.close();
		return card;
	}
}
